import { WeaTools } from "ecCom";


/*
* 友好提示的下载方法
* */


function createATag(iframe) {
   const iDocument = iframe.contentWindow.document;
   const Tag = iDocument.createElement("a");
   Tag.setAttribute("id", "Download"); Tag.setAttribute("download", "error.log");
   iDocument.body.insertAdjacentElement("beforeEnd", Tag);
   return Tag;
}


function getIframe() {
   const ID = "WeaDoc-FileDownload", already = document.getElementById(ID);
   if (already) return already;
   const iframe = document.createElement("iframe");
   iframe.setAttribute("id", ID); iframe.setAttribute("name", ID); iframe.style.display = "none";
   document.body.insertAdjacentElement("beforeEnd", iframe);
   return iframe;
}

function iframeLoad(e) {
   console.log("iframe load事件", e);
   try{
      const iframe = document.getElementById("WeaDoc-FileDownload");
      const body = iframe.contentWindow.document.body;
      // todo 反馈信息待完善
      if (body.firstChild === null || body.firstChild.tagName === "PRE") {
         let text = body.innerText;
         if (text.length > 0) {
            alert(text);
         }else {
            alert("没有下载内容");
         }
      }
      if (body.childElementCount > 1) {
         alert("不是服务端的异常");
      }
   }catch (e) {
      let crossOrigin = e.toString().includes("cross-origin");
      crossOrigin && alert("异源下载异常");
   }
}


// 参数：param: URL or ID
function DocFileDownload(param) {
   const URL = typeof param === "string" && param.includes("?") ? param : `/weaver/weaver.file.FileDownload?fileid=${param}&download=1`;
   WeaTools.callApi(URL, "HEAD", {}).then(res => {
      console.log("HTTP状态码200", res);
      const iframe = getIframe();
      iframe.addEventListener("load", iframeLoad);
      iframe.setAttribute("src", "https://qd.myapp.com/myapp/qqteam/pcqq/PCQQ2019.exe1");
   })
}


export default DocFileDownload;